package cmd

import (
	"context"
	"flag"
	"fmt"
	"mi/compiler/program"
	errors "mi/internal/xerrors"
	"mi/internal/xpath"
	"os"
)

type compileOptions struct {
	Diagnostics                bool
	ExtendedDiagnostics        bool
	ListFiles				   bool
	Run						   bool
	Files                      []xpath.URI
}

// Build implements the Build cmd.
type Build struct {
	RunAfter				   bool     `flag:"run" help:"生成成功后运行"`
	Diagnostics                bool		`flag:"diagnostics" help:"打印诊断信息。"`
	ExtendedDiagnostics        bool		`flag:"extendedDiagnostics" help:"更加详细的诊断信息。"`
	ListFiles				   bool		`flag:"listFiles" help:"打印编译的文件。"`
}

func (b *Build) Name() string      { return "build" }
func (b *Build) Usage() string     { return "" }
func (b *Build) ShortHelp() string { return "生成" }
func (b *Build) DetailedHelp(f *flag.FlagSet) {
	fmt.Fprint(f.Output(), ``)
	f.PrintDefaults()
}

func (b *Build) Run(ctx context.Context, args ...string) error {
	var files = args

	if len(files) == 0 {
		dir, err := os.Getwd()
		if err != nil {
			return err
		}
		var modPath = xpath.CombinePaths(dir, "项目.mip")
		if xpath.PathExistsNoErr(modPath) {
			files = append(files, modPath)
		} else {
			return errors.New("当前目录下未发现 '项目.mip' 文件")
		}
	}

	var uris []xpath.URI
	for _, file := range files {
		uris = append(uris, xpath.URIFromPath(file))
	}

	compile(compileOptions{
		Diagnostics:         b.Diagnostics,
		ExtendedDiagnostics: b.ExtendedDiagnostics,
		ListFiles:           b.ListFiles,
		Files:               uris,
		Run:                 b.RunAfter,
	}, program.CreateCompilerHost())
	return nil
}

